package xyz.lisys.advice.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@Slf4j
@ControllerAdvice
public class GlobalController {
    // 核心作用是 横切多个控制器，提供全局化的处理逻辑，使代码更简洁、可维护

    @ModelAttribute("preToken")
    public String modelAttribute() {
        log.info("modelAttribute preToken | {}", "预先注册内容");
        return "preToken";
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        log.info("initBinder | {}", "当前控制器注册一个属性编辑器");
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public HashMap<String, Object> exceptionHandler(Exception e) {
        log.info(String.valueOf(e));

        HashMap<String, Object> map = new HashMap<>();

        // 注意不加ResponseBody认为status为状态码
        map.put("status", 400);
        map.put("message", "全局捕获异常");

        return map;
    }
}
